#include "app_pool.h"
#include "log/log.h"
#include "mqueue.h"
#include "pthread.h"
#include "stdlib.h"

// 消息队列名称
static char *mq_name = "/app_pool_mq";
// 消息队列描述
static mqd_t mqd;
// 线程池线程数
static int app_pool_thread_num;
// 线程池线程指针
static pthread_t *app_pool_threads;

static void *app_pool_thread_fun(void *arg)
{
    // 不断地从消息队列中获取任务并执行
    Task task;
    while (1)
    {
        ssize_t len = mq_receive(mqd,(char *)&task,sizeof(Task),NULL);
        if (len == sizeof(Task))
        {
            task.task_fun(task.argv);
        }
    }
}
int app_pool_init(int thread_num)
{
    // 1.创建消息队列
    struct mq_attr attr;
    // 设置消息队列属性，最大消息数5，消息大小sizeof(Task)
    attr.mq_maxmsg = 5;
    attr.mq_msgsize = sizeof(Task);
    mqd = mq_open(mq_name, O_CREAT | O_RDWR, 0644, &attr);
    if (mqd == -1)
    {
        log_error("创建或打开消息队列失败");
        return -1;
    }

    // 2.创建线程池
    app_pool_thread_num = thread_num;
    app_pool_threads = (pthread_t *)malloc(app_pool_thread_num * sizeof(pthread_t));
    // 循环创建线程
    for (int i = 0; i < app_pool_thread_num; i++)
    {
        pthread_create(app_pool_threads + i, NULL, app_pool_thread_fun, NULL);
    }

    return 0;
}

void app_pool_destroy()
{
    // 1.停止所有线程
    for (int i = 0; i < app_pool_thread_num; i++)
    {
        pthread_cancel(app_pool_threads[i]);
        // 等待线程结束 获取线程的返回值
        pthread_join(app_pool_threads[i], NULL);
    }
    free(app_pool_threads);

    // 2.关闭删除任务队列
    mq_close(mqd);
    mq_unlink(mq_name);
}

void app_pool_registerTask(int(*task_fun)(void *), void *arg)
{
    Task task = {
        .task_fun = task_fun,
        .argv = arg,
    };
    // 将任务发送到消息队列中
    mq_send(mqd, (char *)&task, sizeof(Task), 0);
}
